using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Globalization;
using System.Net;
using System.Threading;

namespace WindowsApplication4
{
    public partial class MDIParent1 : Form
    {
        private int childFormNumber = 0;

        public MDIParent1()
        {
            InitializeComponent();
        }

        private void ShowNewForm(object sender, EventArgs e)
        {
            // Create a new instance of the child form.
            Form childForm = new Form();
            // Make it a child of this MDI form before showing it.
            childForm.MdiParent = this;
            childForm.Text = "Window " + childFormNumber++;
            childForm.Show();
        }

        private void OpenFile(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = openFileDialog.FileName;
                // TODO: Add code here to open the file.
            }
        }

        private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            saveFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = saveFileDialog.FileName;
                // TODO: Add code here to save the current contents of the form to a file.
            }
        }

        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void CutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // TODO: Use System.Windows.Forms.Clipboard to insert the selected text or images into the clipboard
        }

        private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // TODO: Use System.Windows.Forms.Clipboard to insert the selected text or images into the clipboard
        }

        private void PasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // TODO: Use System.Windows.Forms.Clipboard.GetText() or System.Windows.Forms.GetData to retrieve information from the clipboard.
        }

        private void ToolBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStrip.Visible = toolBarToolStripMenuItem.Checked;
        }

        private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void TileVerticalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }

        private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.ArrangeIcons);
        }

        private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in MdiChildren)
            {
                childForm.Close();
            }
        }

        Map frmMap;
        ControlCenter frmControls;
        CompaingView frmCompaignView;

        private void MDIParent1_Load(object sender, EventArgs e)
        {
            ChooseWorld cw = new ChooseWorld();
            if (cw.ShowDialog() != DialogResult.OK)
            {
                Application.Exit();
                return;
            }
            else
            {
                cw.Close();
            }

            this.Text = "TW++  World " + WindowsApplication4.Properties.Settings.Default.world + " Server : " + Common.GetServerName(WindowsApplication4.Properties.Settings.Default.Servertype);

            if (WindowsApplication4.Properties.Settings.Default.TimeAdjustment == -99)
            {
                CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentUICulture;
                //                culture.Calendar.

                WindowsApplication4.Properties.Settings.Default.TimeAdjustment = 6;

                SetupTimeZone frmsetup = new SetupTimeZone();
                frmsetup.ShowDialog();
            }

            try
            {
                World d = Worlds.currentWorld;
            }
            catch (TypeInitializationException)
            {
                this.Close();
                return;
            }

            frmCompaignView = new CompaingView();

            frmMap = new Map(Worlds.currentWorld, frmCompaignView);
            frmMap.MdiParent = this;
            frmMap.Show();

            Map2 frmMap2 = new Map2(Worlds.currentWorld);

            frmControls = new ControlCenter(frmMap, frmMap2);
            frmControls.MdiParent = this;
            frmControls.Show();

            frmCompaignView.MdiParent = this;
            frmCompaignView.Show();
            frmCompaignView.Visible = false;

            backgroundWorker1.RunWorkerAsync();

            MaxMap();
        }

     

        private void downloadLatestDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!Worlds.currentWorld.DownloadData())
            {
                //if download fails
                this.Close();
                return;
            }


            if (!Worlds.currentWorld.downloadCanceled)
            {
                MessageBox.Show("Download Successful." + Environment.NewLine + Environment.NewLine
                    + "TW++ must be restarted and will now close." + Environment.NewLine + Environment.NewLine
                    , "Restart", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                this.Close();
            }

            
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Tribal Wars++\nVersion " 
                //+ Assembly.GetExecutingAssembly().GetName().Version.ToString(4)
                + App.version 
                , "TW++", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Options frmO = new Options();
            frmO.ShowDialog();
        }

        private void maximizeMapToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MaxMap();
        }

        private void MaxMap()
        {
            MdiClient client;
            client = new MdiClient();

            frmControls.Height = this.ClientRectangle.Height - menuStrip.Height - 5;
            frmControls.Location = new Point(0, 0);

            frmMap.Height = frmControls.Height;
            frmMap.Width = this.ClientRectangle.Width - 5 - frmControls.Width;
            frmMap.Location = new Point(frmControls.Width, 0);

            frmMap.RedrawMap();
        }

        private void MDIParent1_ResizeEnd(object sender, EventArgs e)
        {
            if (resized && WindowsApplication4.Properties.Settings.Default.Autoresize)
            {
                MaxMap();
                resized = false;
            }
        }

        private void MDIParent1_SizeChanged(object sender, EventArgs e)
        {
           

        }

        bool resized = false;
        private void MDIParent1_Resize(object sender, EventArgs e)
        {
            resized = true;

        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmMap.SaveMapToFile();
        }

        private void arrangeWindowsMaxMapToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MaxMap();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            frmCompaignView.Visible = true;
            frmCompaignView.Activate();
            frmCompaignView.WindowState = FormWindowState.Normal;

        }

        private void menuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            StartupCheck.startup startup = new WindowsApplication4.StartupCheck.startup();

            if (WindowsApplication4.Properties.Settings.Default.useProxy)
            {
                WebProxy myProxy = new WebProxy();
                myProxy.Address = new Uri(WindowsApplication4.Properties.Settings.Default.proxyAddress);
                myProxy.UseDefaultCredentials = true;
                startup.Proxy = myProxy;

            }

            string response=string.Empty;
            try
            {
                response = startup.StartupCheck(App.version);


                //
                // DEBUG VERSION
                //localhost_StartupCheck.startup debug_startup= new WindowsApplication4.localhost_StartupCheck.startup();
                //response = debug_startup.StartupCheck(App.version);
            }
            catch (Exception )
            {
                DialogResult result = MessageBox.Show("Error while checking for latest release information." + Environment.NewLine + Environment.NewLine
                    + "TW++ checks for latest release information at startup but it failed. This could be due to temporary network failure but if you also experience problems downloading latest world data, then perhaps you need to configure your network settings." + Environment.NewLine + Environment.NewLine
                    + "If you click OK, then network settings windows will be launched. Click Cancel to skip" + Environment.NewLine + Environment.NewLine
                    , "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);

                if (result == DialogResult.OK)
                {
                    Options frm = new Options();
                    frm.ShowDialog();
                }
            }

            if (!string.IsNullOrEmpty(response))
            {
                if (response.StartsWith("http://"))
                {
                    System.Diagnostics.Process.Start(response); 
                }
                else
                {
                    StartupInformation frm = new StartupInformation(response);

                    frm.ShowDialog();
                }
            }
           

        }

       

        private void chooseAnotherWorldToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Restart();
        }

        private void contentsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://forum.twplus2.com"); 
        }


        //protected override void WndProc(ref Message m)
        //{
        //    if (m.Msg == 0x0112) // Test for WM_SYSCOMMAND
        //        if (((int)m.WParam & 0xFFF0) == 0xF030)   // Test for SC_MINIMIZE
        //        {
        //            base.WndProc(ref m);
        //            MaxMap();
        //        }
        //}

    }
}
